package com.whpu.mall.product.service.impl;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whpu.common.constant.ProductConstant;
import com.whpu.common.to.SkuReductionTo;
import com.whpu.common.to.SpuBoundTo;
import com.whpu.common.to.es.SkuEsModel;
import com.whpu.common.utils.PageUtils;
import com.whpu.common.utils.Query;
import com.whpu.common.utils.R;
import com.whpu.mall.product.dao.SpuInfoDao;
import com.whpu.mall.product.entity.*;
import com.whpu.mall.product.feign.CouponFeignService;
import com.whpu.mall.product.feign.SearchFeignService;
import com.whpu.mall.product.feign.WareFeignService;
import com.whpu.mall.product.service.*;
import com.whpu.mall.product.vo.SkuHasStockVo;
import com.whpu.mall.product.vo.spu.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService descService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private ProductAttrValueService attrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 保存商品信息
     *
     * @param spuVo
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveSpuInfo(SpuSaveVo spuVo) {

        //1、保存spu的基本信息 pms_spu_info
        SpuInfoEntity spuInfo = new SpuInfoEntity();
//        spuInfo.setCreateTime(new Date());    //使用mybatis-plus自动填充字段,就不用设置了
//        spuInfo.setUpdateTime(new Date());
        BeanUtils.copyProperties(spuVo, spuInfo);
        this.saveSpuBaseInfo(spuInfo);

        //2、保存spu的描述信息 pms_spu_info_desc
        List<String> descriptions = spuVo.getImages();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(spuInfo.getId());
        descEntity.setDecript(String.join(",", descriptions));
        descService.saveSpuDescInfo(descEntity);

        //3、保存spu的图片集 pms_spu_images
        List<String> images = spuVo.getImages();
        spuImagesService.saveImages(spuInfo.getId(), images);

        //4、保存spu的规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuVo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setAttrId(attr.getAttrId());
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            valueEntity.setAttrName(attrEntity.getAttrName());
            valueEntity.setAttrValue(attr.getAttrValues());
            valueEntity.setQuickShow(attr.getShowDesc());
            valueEntity.setSpuId(spuInfo.getId());

            return valueEntity;
        }).collect(Collectors.toList());
        attrValueService.saveProductAttr(collect);

        //5、保存spu的积分信息 mall_sms -> sms_spu_bounds
        Bounds bounds = spuVo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(spuInfo.getId());

        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if (r.getCode() != 0) {
            log.error("调用远程保存spu的积分信息失败");
        }

        //6、保存spu所有对应的sku信息
        //6.1、sku的基本信息 pms_sku_info
        List<Skus> skus = spuVo.getSkus();
        if (skus != null && skus.size() > 0) {  //有信息就遍历
            skus.forEach(item -> {
                //图片处理,判断是否是默认图片
                String defaultImg = "";
                for (Images image : item.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfo.getBrandId());
                skuInfoEntity.setCatalogId(spuInfo.getCatalogId());
                skuInfoEntity.setSaleCount(0L);  //默认值
                skuInfoEntity.setSpuId(spuInfo.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);   //默认图片
                //6.1、sku的基本信息 pms_sku_info
                skuInfoService.saveSkuInfo(skuInfoEntity);  //保存sku的基本信息
                Long skuId = skuInfoEntity.getSkuId();

                List<SkuImagesEntity> imagesList = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);  //关联的skuId
                    skuImagesEntity.setImgUrl(img.getImgUrl());  //关联的图片地址
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(target -> {
                    return StringUtils.isNotEmpty(target.getImgUrl());
                }).collect(Collectors.toList());

                //6.2、sku的图片信息 pms_sku_images
                skuImagesService.saveBatch(imagesList);
                //TODO 没有图片路径的无需保存


                //6.3、sku的销售属性信息 pms_sku_sale_attr_value
                List<Attr> attrs = item.getAttr();
                List<SkuSaleAttrValueEntity> attrValueList = attrs.stream().map(attr -> {
                    SkuSaleAttrValueEntity saleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, saleAttrValueEntity);
                    saleAttrValueEntity.setAttrId(skuId);
                    return saleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(attrValueList);

                //6.4、sku的优惠等信息 mall_sms -> sms_sku_ladder/sms_sku_full_reduction/sms_member_price
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item, skuReductionTo);
                skuReductionTo.setSkuId(skuId);

                //当满几件或者满多少金额时有实际意义,也就是大于0的时候调用远程服务保存优惠信息.因为优惠信息和满减是两张表,所以用||
                //当有会员价格时也调用
                if (skuReductionTo.getFullCount() > 0
                        || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1
                        || skuReductionTo.getMemberPrice().size() > 0) {
                    R cr = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (cr.getCode() != 0) {
                        log.error("调用远程保存sku的优惠等信息失败");
                    }
                }


            });
        }


    }

    /**
     * 保存spu的基本信息
     *
     * @param spuInfo
     */
    @Override
    public void saveSpuBaseInfo(SpuInfoEntity spuInfo) {
        this.baseMapper.insert(spuInfo);
    }

    /**
     * 条件分页查询
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {

        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();

        /**
         *  key:
         *  status: 0
         *  brandId: 0(没选)
         *  catelogId: 165
         */
        //搜索关键词
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            //这里有or,需要加上and包起来拼接,否则会出现 status=1 and id=1 or spu_name like 1
            //or后面的条件一旦成立前面就失效了,所以需要用()包起来status=1 and (id=1 or spu_name like 1)
            wrapper.and(w -> {  //模糊查询id或者名字
                w.eq("id", key).or().like("spu_name", key);
            });
        }
        //状态 - 0:新建,1:上架,2:下架
        String status = (String) params.get("status");
        if (StringUtils.isNotEmpty(status)) {
            wrapper.eq("publish_status", status);
        }
        //品牌
        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            wrapper.eq("brand_id", brandId);
        }
        //分类
        String catelogId = (String) params.get("catelogId");
        if (StringUtils.isNotEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );


        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {



        //1.查询当前spu对应的sku信息
        List<SkuInfoEntity> skus = skuInfoService.getSkuBySpuId(spuId);

        //4.查询当前sku的所有可以被用来检索的规格属性
        List<ProductAttrValueEntity> baseAttrs = attrValueService.baseSpuList(spuId);
        List<Long> attrIds = baseAttrs.stream().map(item -> item.getAttrId()).collect(Collectors.toList());

        Set<Long> idSet = attrService.selectSearchAttrIds(attrIds);

        List<SkuEsModel.Attrs> attrsList = baseAttrs.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attrs1 = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs1);
            return attrs1;
        }).collect(Collectors.toList());

        //发送远程调用，查询sku是否有库存,为了不影响正常的业务逻辑，进行try catch
        Map<Long, Boolean> stockMap = null;
        try {
            List<Long> skuIdList = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
            R skusHasStock = wareFeignService.getSkusHasStock(skuIdList);
            //获取R里的data数据转为的对象引用,TypeReference为protected类型，所以使用内部类的方式创建
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>(){};
            //转为map,key:skuId,value:是否有库存
            stockMap = skusHasStock.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
        }catch (Exception e){
            log.error("查询sku库存失败, 原因:{}", e);
        }

        //2.封装sku的信息
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> upProducts = skus.stream().map(sku -> {
            SkuEsModel esModel = new SkuEsModel();
            BeanUtils.copyProperties(sku, esModel);
            esModel.setSkuPrice(sku.getPrice());
            esModel.setSkuImg(sku.getSkuDefaultImg());
            //远程请求是否有库存
            //esModel.setHasStock(finalStockMap.getOrDefault(sku.getSkuId(),true));
            esModel.setHasStock(MapUtil.isEmpty(finalStockMap)?true:finalStockMap.get(sku.getSkuId()));

            //TODO 热度评分
            esModel.setHotScore(0L);
            //查询品牌分类和名称
            BrandEntity brand = brandService.getById(esModel.getBrandId());
            CategoryEntity category = categoryService.getById(esModel.getCatalogId());
            esModel.setBrandName(brand.getName());
            esModel.setBrandImg(brand.getLogo());
            esModel.setCatalogName(category.getName());
            //设置检索属性
            esModel.setAttrs(attrsList);


            return esModel;
        }).collect(Collectors.toList());

        //5. 将数据发送es进行保存
        R res = searchFeignService.productStatusUp(upProducts);
        if (res.getCode() == 0){
            //上架成功，更新当前spu的状态
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else {
            //上架失败
            //TODO 7、重复调用？接口幂等性以及失败重试机制
        }

    }

}
